"""Configuration settings for AncientSeeker backend."""

from __future__ import annotations

import os
from pathlib import Path
from typing import List, Any

from pydantic_settings import BaseSettings
from pydantic import field_validator


class Settings(BaseSettings):
    # Basic app
    APP_NAME: str = "AncientSeeker"
    VERSION: str = "0.1.0"
    DEBUG: bool = False
    # 监听地址：改为 0.0.0.0 以便局域网其它机器可访问（生产环境可再收紧）
    HOST: str = "0.0.0.0"
    PORT: int = 8000

    # DB
    DATABASE_URL: str = "sqlite:///./data/database.db"

    # Security
    SECRET_KEY: str = "dev_change_me"  # override in production
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30

    # CORS (comma separated or JSON list)
    ALLOWED_ORIGINS: List[str] = [
        "http://localhost:3000",
        "http://localhost:5173",
        "http://127.0.0.1:5173",
        "http://localhost:5174",
        "http://127.0.0.1:5174",
        "http://localhost:8080",
        "http://127.0.0.1:8080",
        "http://localhost:3001",
        "http://127.0.0.1:3001",
    ]

    # AI Configuration (Generic)
    AI_API_URL: str = ""  # LLM API endpoint
    AI_API_KEY: str = ""  # API key
    AI_MODEL_NAME: str = ""  # Model name

    # Image Generation AI Configuration
    IMAGE_AI_API_URL: str = ""  # Image generation API endpoint
    IMAGE_AI_API_KEY: str = ""  # Image API key
    IMAGE_AI_MODEL_NAME: str = ""  # Image model name

    # File / AI limits
    MAX_FILE_SIZE: int = 10485760
    UPLOAD_DIR: str = "./data/uploads"
    AI_RESPONSE_MAX_LENGTH: int = 2000
    IMAGE_GENERATION_TIMEOUT: int = 60
    AI_REQUEST_TIMEOUT: int = 120  # AI请求超时时间（秒）

    # Control whether deleting image record also removes physical file
    AI_IMAGE_PHYSICAL_DELETE: bool = True

    # Data directories
    BOOKS_DATA_DIR: str = ""  # 可通过环境变量覆盖，若为空则在运行时解析为绝对路径

    @field_validator("ALLOWED_ORIGINS", mode="before")
    @classmethod
    def parse_origins(cls, v: Any):  # type: ignore
        if isinstance(v, str):
            text = v.strip()
            if text.startswith("[") and text.endswith("]"):
                return v  # let pydantic parse JSON array
            return [item.strip() for item in text.split(",") if item.strip()]
        return v

    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"
        case_sensitive = True


settings = Settings()

# 解析并创建数据目录（绝对路径确保一致性）
try:
    # 项目根目录: backend/app/config.py -> parents[2] == 项目根
    project_root = Path(__file__).resolve().parents[2]

    if not settings.BOOKS_DATA_DIR:
        # 默认指向 backend/data/books 目录（绝对路径）
        default_books_dir = project_root / "backend" / "data" / "books"
        settings.BOOKS_DATA_DIR = str(default_books_dir)

    # 规范化UPLOAD_DIR为绝对路径（保持向后兼容：若原先是相对路径则基于当前工作目录创建）
    upload_dir_path = Path(settings.UPLOAD_DIR)
    if not upload_dir_path.is_absolute():
        # 不强制转换为绝对路径，避免破坏已存在行为；仅确保目录存在
        os.makedirs(settings.UPLOAD_DIR, exist_ok=True)
    else:
        upload_dir_path.mkdir(parents=True, exist_ok=True)

    # 创建 images 与 books 目录
    os.makedirs(
        "./data/images", exist_ok=True
    )  # 保留旧路径兼容（若有脚本依赖相对路径）
    Path(settings.BOOKS_DATA_DIR).mkdir(parents=True, exist_ok=True)
except Exception as e:
    # 仅记录，不阻断应用启动
    import logging

    logging.getLogger(__name__).warning(f"Failed initializing data directories: {e}")
